<!--
权限控制页
单仕瑞
2017年4月14日 11:51:50
-->
<template>
  <div v-loading="loading">
    <!--权限控制-->
    <el-form :model="roleEntity" label-width="80px" :rules="roleFormRules" ref="role" style="margin:0 auto">
      <el-form-item label="角色名称" prop="roleName" id="roleNameClass">
        <el-input v-model="roleEntity.roleName" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDes">
        <el-input v-model="roleEntity.roleDes" type="textarea" id="roleDesClass" resize="none" :maxlength="255"></el-input>
      </el-form-item>
      <el-tabs type="card" id="menuClass">
        <el-tab-pane v-for="(menu, index) in menuListData" :key="index"  :label="menu.menuName">
          <!--<el-tree :data="menu.childNode" show-checkbox default-expand-all  node-key="id" ref="tree" highlight-current :props="defaultProps" :default-checked-keys="checkedKeys">
          </el-tree>-->
          <tree-menu :model="menu" ref="tree" :menuList="menu" :label="index" :selectKeys="checkedKeys"></tree-menu>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <div scope="footer" class="dialog-footer" id="actionClass">
      <el-button @click.native="goback">取消</el-button>
      <el-button type="primary" @click.native="update" :loading="saveMenuLoading">保存</el-button>
    </div>
    <!--登录超时提示框-->
    <!--<el-col>
      <el-dialog :title="tipsTitle" v-model="diaAlert" size="small" @close="aginLogin" style="top:10%">
        <div align="center">登录超时，请重新登录</div>
        <span slot="footer" class="dialog-footer" align="center">
            <el-button type="primary" @click="aginLogin">确 定</el-button>
          </span>
      </el-dialog>
    </el-col>-->
  </div>
</template>

<script type="text/ecmascript-6">
  import treeMenu from './treePlugin/treeMenu.vue'
  import {sortByMenuTop, sessionOut} from '../../smartlight/common/js/util.js'
  export default {
    // props: {
    //   roleEntity: {
    //     type: Object
    //   }
    // },
    data () {
      return {
        singleMenuFlag: false, // 独一级菜单结合
        saveMenuLoading: false,
        loading: true,
        scrollY: 0,
        menuListData: [], // 菜单数据
        menuList: [], // 所有菜单
        checkedKeys2: [],
        checkedKeys: [],
        checkedKeyAlls: [],
        updateData: [],
        tipsTitle: '提示',
        diaAlert: false, // 控制展示登录超时
        defaultProps: {
          children: 'childNode',
          label: 'menuName'
        },
        roleFormRules: {
          roleName: [
            {required: true, message: '请输入角色名称', trigger: 'blur'}
          ],
          roleDes: [
            {max: 255, message: '最多输入255个字符', trigger: 'blur'}
          ]
        },
        roleEntity: {
          id: '',
          accountType: '',
          roleName: '',
          companyId: '',
          roleDes: '',
          menu: ''
        }
      }
    },
    methods: {
      checkIfLogin () { // 判断是否登录超时--单仕瑞--2017年4月25日 16:41:30
        var user = sessionStorage.getItem('user')
        if (!user) {
          this.diaAlert = true
          return false
        } else {
          return true
        }
      },
      aginLogin () { // 登录超时后点击【确定】按钮事件--单仕瑞--2017年4月25日 16:36:53
        this.diaAlert = false
        sessionStorage.removeItem('user')
        this.$router.push({path: '/login'})
      },
      goback () {
        // this.$emit('clickbutton', '')
        this.$router.push({path: '/baseRole'})
        this.$store.dispatch('updatelocationpath', '/baseRole')
      },
      deleteFatherNodes (menu, list) { // 找到需要删除的父节点--单仕瑞--2017年4月14日 11:51:50
        for (var i = 0; i < menu.length; i++) {
          var item = menu[i]
          try {
            if (item.childNode && item.childNode.length > 0) {
              this.deleteFatherNodes(item.childNode, list)
            } else {
              list.push(item.id)
            }
          } catch (e) {
            console.log('递归函数异常！')
          }
        }
      },
      update () {
        this.loading = true
//        if (!this.checkIfLogin()) {
//          return
//        }
        for (var i = 0; i < this.$refs.tree.length; i++) {
          // this.updateData.push(this.$refs.tree[i].getCheckedKeys())
          this.updateData.push(this.$refs.tree[i].getAllKeys())
        }
        this.saveMenuLoading = true
        this.$http.post('/smartLight/web/sysRole/saveRole.htm', {updateData: this.updateData, role: this.roleEntity, type: this.roleEntity.accountType}).then(response => {
          this.saveMenuLoading = false
          var resBody = response.body
          if (resBody.isSuccess === 0) {
            let menus = resBody.result
            if (menus !== '') {
              sessionStorage.setItem('buttonIds', menus)
            }
            this.showAdd = false
            this.addLoading = false
            this.$message({
              showClose: true,
              message: '操作成功',
              type: 'success'
            })
            // this.goback() // 触发【取消】按钮
            // this.$emit('initRoleList', '') // 回到角色列表页面后再次重新查询角色列表
            this.$router.push({path: '/baseRole'})
            this.$store.dispatch('updatelocationpath', '/baseRole')
          } else if (resBody.isSuccess === 2) {
            this.listLoading = false
            sessionOut(this) // session超时处理
          } else {
            this.$message({
              showClose: true,
              message: resBody.errorMsg,
              type: 'error'
            })
          }
        })
        this.loading = false
      }
    },
    computed: {
      _menuList () {
        this.menuList = []
//        this.deleteFatherNodes(this.menuList, this.checkedKeyAlls)
      }
    },
    created () {
      var para = {
        accountType: this.$route.params.accountType, // this.roleEntity.accountType, // 登录者的帐号类型（运营or供应or采购or个人）
        type: this.$route.params.type, // this.roleEntity.accountType,
        roleId: this.$route.params.roleId
      }
      if (para.accountType === undefined) { // 权限控制页面刷新操作，转向角色管理页面
        this.$router.push({path: '/baseRole'})
        return
      }
      this.$http.post('/smartLight/web/baseMenu/getByAll.htm', para).then(response => {
        var resBody = response.body
        let isSuccess = resBody.isSuccess
        if (isSuccess === 0) {  // 成功
          this.roleEntity = resBody.roleEntity
          this.menuList = resBody.menuList
          // 菜单排序
          sortByMenuTop(this.menuList)
          if (this.menuList.length === 1) {
            this.singleMenuFlag = true
            this.menuListData = this.menuList[0].childNode
          } else {
            this.menuListData = this.menuList
          }
          // this.menuListData = this.menuList
          this.deleteFatherNodes(this.menuList, this.checkedKeyAlls)
          if (resBody.selMenuList) {
            this.deleteFatherNodes(resBody.selMenuList, this.checkedKeys)
          }
          for (var i = 0; i < this.checkedKeys.length; i++) {
            if (this.checkedKeyAlls.toString().indexOf(this.checkedKeys[i].toString()) > -1) {
              this.checkedKeys2.push(this.checkedKeys[i])
            }
          }
          // this.checkedKeys = this.checkedKeys2 // element-tree插件使用
          if (resBody.menuArr && resBody.menuArr.length) { // treeMenu插件使用
            this.checkedKeys = resBody.menuArr
          }
        } else if (isSuccess === 2) {  // 超时
          this.loading = false
          this.$alert(resBody.errorMsg, {
            type: 'warning'
          }).then(() => {
            this.$router.push({path: '/login'})
            sessionStorage.clear()
          })
        } else {  // 其他情况
          this.$message({
            showClose: true,
            message: resBody.errorMsg,
            type: 'error'
          })
        }
      })
      this.loading = false
    },
    components: {
      treeMenu
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
  .tabRow
    font-size: 12px;
  .button-align
    float: right;
  #menuClass
    margin-left:80px;
  #roleNameClass
    width 500px;
  #roleDesClass
    width 420px;
  #actionClass
    margin-top 15px;
    margin-left 520px;
  .el-tree-node__children>.el-tree-node>.el-tree-node__children .el-tree-node
    float left;
    width 200px;
</style>
